import { jwtDecode } from 'jwt-decode'

interface IObject {
    [key: string]: any
}

// 嵌套深拷贝
function deepCopy(value: IObject | Array<any>) {
    if (Object.keys(value).length <= 0) return value
    if (Array.isArray(value)) {
        const result: any[] = []
        value.forEach((item) => {
            result.push(deepCopy(item))
        })
        return result
    } else {
        const result: IObject = {}
        Object.keys(value).forEach((key) => {
            result[key] = deepCopy(value[key])
        })
        return result
    }
}

// 简易深拷贝
function simpleDeepCopy(value: Object | Array<any>) {
    return JSON.parse(JSON.stringify(value))
}

// 通过token获取用户信息
function getUserInfoByToken() {
    const token = localStorage.getItem('token') || ''
    const userInfo: {
        username: string
    } = jwtDecode(token)
    return userInfo
}

export default {
    deepCopy,
    simpleDeepCopy,
    getUserInfoByToken,
}
